package com.greendragon.persistence.dao.impl; 

import java.sql.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.greendragon.persistence.dao.IOrderDao;
import com.greendragon.persistence.domain.Order;
import com.greendragon.persistence.enmu.FetchOrderType;
import com.greendragon.persistence.enmu.LockType;


/** 
 * @author wulibin, exceptsky@gmail.com, 2011-9-8 下午11:25:09
 * 
 */
@SuppressWarnings("unchecked")
public class OrderDaoImpl extends BaseDao<Order> implements IOrderDao{
	private static Logger          logger           = Logger.getLogger(OrderDaoImpl.class);
	@Override
	public List<Order> getByDate(Date startDate, Date endDate, int offset, int length, LockType lockType, FetchOrderType orderType) {
		String hql = "from Order as o where o.createdAt between ? and ?"+getLockSql("o", lockType)+getOrderSql("o", orderType);
		return selectByPage(hql, new Date[]{startDate, endDate}, offset, length);
	}

	@Override
	public long getCountByDate(Date startDate, Date endDate, LockType lockType) {
		String hql = "select count(o.id) from Order as o where o.createdAt between ? and ?"+getLockSql("o", lockType);
		try {
			List rs = getHibernateTemplate().find(hql, new Date[]{startDate, endDate});
			if(rs==null || rs.size()==0){
				return 0l;
			}
			long count = (Long)rs.listIterator().next();
			return count;
		} catch (Exception e) {
			logger.error(e);
			return 0l;
		}
	}

	@Override
	public long getCountByUser(long uid, LockType lockType) {
		String hql = "select count(o.id) from Order as o where o.author.id=?"+getLockSql("o", lockType);
		try {
			List rs = getHibernateTemplate().find(hql, uid);
			if(rs==null || rs.size()==0){
				return 0l;
			}
			long count = (Long)rs.listIterator().next();
			return count;
		} catch (Exception e) {
			logger.error(e);
			return 0l;
		}
	}

	@Override
	public List<Order> getByUser(long uid, int offset, int length,  LockType lockType, FetchOrderType orderType) {
		String hql = "from Order as o where o.author.id=?"+getLockSql("o", lockType)+getOrderSql("o", orderType);
		return selectByPage(hql, new Long[]{new Long(uid)}, offset, length);
	}

}
 